package fx.mine.active.component.util;

import lombok.extern.log4j.Log4j2;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

@Log4j2
public class HttpUtil {
    public static final OkHttpClient CLIENT = new OkHttpClient.Builder()
            .callTimeout(3, TimeUnit.SECONDS)
            .build();

    public static void sseCallBack(Consumer<String> consumer) {
        //快讯示例
//            {"type":"data","cname":"bdc02c361aab973818f3583fb8b5e6d5","seq":61035,"content":"{\"Type\":\"MajorNews\",\"Data\":{\"Art_Code\":\"202209082505288872\",\"Art_Title\":\"23年来首次 欧央行加息75个基点！通胀“捅破天” 德国民众开始洗冷水澡\",\"Art_Sim_Title\":\"重大资讯推送\",\"Art_Docu_Reader\":\"23年来首次，欧央行加息75个基点！通胀“捅破天”，能源价格高涨，德国有些民众已开始洗冷水澡。\",\"Art_ShowTime\":\"2022-09-08T22:06:00\",\"Art_Url\":\"http://finance.eastmoney.com/a/202209082505288872.html\"}}"}

        String url = "http://19.push2.eastmoney.com/api/qt/stock/sse?fields=f58,f107,f57,f43,f59,f169,f170,f152,f46,f60,f44,f45,f47,f48,f19,f532,f39,f161,f49,f171,f50,f86,f600,f601,f154,f84,f85,f168,f108,f116,f167,f164,f92,f71,f117&mpi=1000&invt=2&fltt=1&secid=106.BABA&ut=fa5fd1943c7b386f172d6893dbfba10b&wbp2u=|0|0|0|web";
        Request request = new Request.Builder()
                .get()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36")
                .build();

        EventSource.Factory factory = EventSources.createFactory(CLIENT);
        EventSource eventSource = factory.newEventSource(request, new EventSourceListener() {
            @Override
            public void onClosed(EventSource eventSource) {
                log.info("closed");
                super.onClosed(eventSource);
            }

            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                consumer.accept(data);
            }

            @Override
            public void onFailure(EventSource eventSource, Throwable t, Response response) {
                super.onFailure(eventSource, t, response);
            }

            @Override
            public void onOpen(EventSource eventSource, Response response) {
                super.onOpen(eventSource, response);
            }
        });
        if (false) {
            eventSource.cancel();
        }
    }
}
